<?php

namespace App\Http\Controllers\Auth;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Traits\Auth\RegisterTrait;
use App\Http\Traits\Auth\SocialiteTrait;
use App\Http\Requests\Auth\RegisterRequest;


class RegisterController extends Controller
{
    use SocialiteTrait, RegisterTrait {
        RegisterTrait::register as baseRegister;
    }

    /**
     * 显示注册页面
     *
     * @return \Illuminate\View\View
     */
    public function showRegister()
    {
        return $this->view('auth.register', [
            'socialite' => $this->getSocialite()
        ]);
    }

    /**
     * 注册
     *
     * @param RegisterRequest $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \Exception
     */
    public function register(RegisterRequest $request)
    {
        $user = $this->baseRegister($request);

        $this->guard()->login($user);

        return $this->intended();
    }

    /**
     * 返回注册数据
     *
     * @param Request $request
     *
     * @return array
     */
    protected function registerData(Request $request)
    {
        $data = $request->only(['name', 'mobile']);

        // 第三方登录数据
        if ($socialite = $this->getSocialite()) {

            $data['avatar'] = $socialite->getAvatar();
            $data['email'] = $socialite->getEmail();
        }

        return $data;
    }

    /**
     * 创建账号
     *
     * @param Request $request
     * @param array $data
     *
     * @return User
     */
    protected function create(Request $request, array $data)
    {
        $user = User::create($data);

        // 创建用户信息
        $user->info()->create([
            'register_ip' => $request->ip()
        ]);

        return $user;
    }

    /**
     * 注册完成
     *
     * @param User $user
     */
    protected function registered(User $user)
    {
        if ($this->hasSocialite()) {

            // 创建第三方账号绑定
            $user->binds()->create($this->getSocialiteData());

            // 清除第三方账号登录状态
            $this->forgetSocialite();
        }
    }
}
